package com.seaside.park.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seaside.common.bean.Result;
import com.seaside.common.util.FormatUtil;
import com.seaside.park.bean.AppVersion;
import com.seaside.park.mapper.AppVersionMapper;
import com.seaside.park.service.ParkService;
import com.seaside.parkCommon.bean.ParkZone;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;


@Api(tags = "公开接口列表")
@Slf4j
@RestController
@RequestMapping("/api/public")
public class PublicAPI {

    @Autowired
    private AppVersionMapper appVersionMapper;

    @Autowired
    private ParkService parkService;
    
    /**
     * 上传路径：/usr/share/nginx/html/
     */
    @Value("${aowo.file.upload.base.path}")
    private String uploadBasePath;

    /**
     * 上传目录：images/cabinet/
     */
    @Value("${aowo.file.upload.base.folder}")
    private String uploadBaseFolder;

    /**
     * 访问路径（域名）：http://www.aowo.vip/
     */
    @Value("${aowo.file.preview.base.path}")
    private String previewBasePath;

    @RequestMapping("/upload")
    public Result<String> upload(HttpServletRequest request) {
        Result result = null;
        String picFolder = uploadBasePath + uploadBaseFolder;
        try {
            request.setCharacterEncoding("utf-8");
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            File folder = new File(picFolder);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            List<String> filePaths = new ArrayList<>();
            while (iterator.hasNext()) {
                MultipartFile multipartFile = req.getFile(iterator.next());
                String originalFirstName = multipartFile.getOriginalFilename();
                String uuid = FormatUtil.getUUID();
                String kzm = originalFirstName.substring(originalFirstName.lastIndexOf("."));
                String filename = uuid + kzm;
                File file = new File(picFolder + filename);
                //真正写到磁盘上
                OutputStream out = new FileOutputStream(file);
                out.write(multipartFile.getBytes());
                out.close();
                filePaths.add(previewBasePath + uploadBaseFolder + filename);
                String filePath = previewBasePath + uploadBaseFolder + filename;
                log.info("图片访问路径：" + filePaths);
                result = Result.OK("图片上传成功!", filePath);
            }
        } catch (Exception e) {
            log.error("图片上传失败!" + e.getMessage());
            result = Result.Error("图片上传失败!" + e.getMessage());
        }
        return result;
    }

    /**
     * 停车场查询
     *
     * @return
     */
    @ApiOperation(value = "停车场查询（带车位）", response = Result.class)
    @PostMapping("/park/zone/list")
    public Result<List<ParkZone>> queryParkZoneList() {
        return parkService.getAllParkZoneWithPlaceList();
    }

    /**
     * 查询最新版本号
     *
     * @return
     */
    @ApiOperation(value = "查询版本信息", response = Result.class)
    @PostMapping("/latest/version")
    public Result<AppVersion> getLatestVersion() {
        QueryWrapper<AppVersion> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("version_id");
        List<AppVersion> versionList = appVersionMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(versionList)) {
            return Result.OK("版本查询正确!", versionList.get(0));
        }
        return Result.Error("暂无版本信息！");
    }

}